clientid="power_"..string.gsub(wifi.sta.getmac(),":","")

mqttCfg={}

if file.open(BootProcessVar.mqqtConfigFile) then
    local StartObjStr=file.read()
    mqttCfg=sjson.decode(StartObjStr)
    file:close()
end
ConnTrm=tmr.create()
m = mqtt.Client(clientid, 120, mqttCfg.mqttName, mqttCfg.mqttPwd)
MQTTconnectFlag=0

ConnTrm:register(5000, tmr.ALARM_SEMI, function() 
    if m~=nil then
        print("Attempting client connect...")
        print(mqttCfg.Ser)
        print(mqttCfg.mqttPort)
        m:connect(mqttCfg.Ser, mqttCfg.mqttPort,0,MQTTSuccess,MQTTFailed)
    end

end)

Topic=mqttCfg.Topic..'/'..clientid
function MQTTSuccess(client)
    print("MQTT connected")
    client:subscribe(Topic,0, function(conn)     --注册topic0
        print("subscribe success") 
        gpio.mode(6,gpio.OUTPUT)-- 注册成功，设置输出模式
        gpio.write(6,1) --设置开机自动上电
    end) 
    m=client
    MQTTconnectFlag=1
    ConnTrm:stop()        --关闭定时连接
end

function MQTTFailed(client,reson)--mqtt错误后回调
    print("Fail reson:"..reson)
    MQTTconnectFlag=0
    ConnTrm:start()       --重新启动连接
end

m:on("message", function(client, Topic, data) --接受到消息

    if data ~= nil then
        local mqttJsonMessage=sjson.decode(data)
        if mqttJsonMessage.clientID==clientid then
            return
        end
        if mqttJsonMessage.power==0 then
            gpio.write(6,0)
        else
            gpio.write(6,1)
        end
        local updata={}
        updata.clientID=clientid
        updata.power=gpio.read(6)
        local updataStr = sjson.encode(updata)
        m:publish(Topic,updataStr,0,0,function(client)
        end)
    end
end)
m:on("offline", function(client) 
    print ("offline") 
    MQTTconnectFlag=0
    ConnTrm:start() 
end)
ConnTrm:start()

--[topic 定时上传数据]
wsdValue={}
tmr.create():alarm(60000,tmr.ALARM_AUTO,function()   --等待连接上
    if MQTTconnectFlag==1 and m~=nil then 
        local updata={}
        updata.clientID=clientid
        updata.power=gpio.read(6)
        local updataStr = sjson.encode(updata)
        m:publish(Topic,updataStr,0,0,function(client)
--            print("send ok" ) 
        end)
        collectgarbage("collect") --回收之前的内存
    end
end)

